import React from 'react'
import { connect } from 'react-redux'
import PubSub from 'pubsub-js'
import { REQUEST_INFO } from '../constant'
import FriendRequestModal from './FriendRequest'
import { acceptRequestInfo } from '../../action/action'

class FriendRequest extends React.PureComponent {
  constructor (props) {
    super(props)
    this.state = {
      visible: false
    }
  }

  onCancel = () => {
    this.setState({
      visible: false
    })
  }

  showModal = () => {
    this.setState({
      visible: true
    })
  }

  componentDidMount () {
    //订阅的事件
    this.pubsub_token = []
    this.pubsub_token.push(PubSub.subscribe(REQUEST_INFO, this.showModal))

  }

  agreeRequest = (item) => {
    // 同意好友申请
    // 调取通过好友请求接口
    const { dispatch } = this.props
    dispatch(acceptRequestInfo({ messageId: item.id, accept: true }))
  }
  refuseRequest = (item) => {
    // 拒绝好友申请
    const { dispatch } = this.props
    dispatch(acceptRequestInfo({ messageId: item.id, accept: false }))
  }

  render () {
    const { visible } = this.state
    const { onCancel, refuseRequest, agreeRequest } = this
    return (
      <FriendRequestModal
        visible={visible}
        onCancel={onCancel}
        data={this.props.requestInfo.toJS()}
        refuseRequest={refuseRequest}
        agreeRequest={agreeRequest}
      />
    )
  }
}

const mapStateToProps = (state) => {
  return {
    requestInfo: state.get('getRequestInfo')
  }
}
export default connect(mapStateToProps)(FriendRequest)